package com.nh.reception.receiver;

import com.alibaba.fastjson.JSONObject;
import com.nh.common.pojo.Log;
import com.nh.reception.service.ReceptionService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
import java.util.Objects;

/**
 * @Author: LaoCao
 * @Date: 2023/3/16 16:30
 * @Version: 1.0
 **/
@Component
public class ReceptionReceiver {
    @Resource
    private ReceptionService receptionService;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "QUEUE_RECEPTION",durable = "true",autoDelete = "false"),
            exchange = @Exchange(value = "EXCHANGE_RECEPTION"),
            key = {"ROUTING_KEY_RECEPTION"}
    ))
    //接收消息获取传递过来的已分析完毕的json字符串数据，转换为集合后进行批量保存至数据库
    public void saveLogResult(Message message, Channel channel,String logJsonStr){
        try {
            List<Log> logList = JSONObject.parseArray(logJsonStr,Log.class);
            logList.removeIf(Objects::isNull);
            //批量添加日志数据
            receptionService.batchLogs(logList);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
